package cn.bocweb.spinning.view.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.nineoldandroids.view.ViewHelper;

import java.io.File;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.GetMsgBean;
import cn.bocweb.spinning.model.Bean.LibListBean;
import cn.bocweb.spinning.model.Bean.SecondHandle2Bean;
import cn.bocweb.spinning.model.Bean.SecondTimeBean;
import cn.bocweb.spinning.model.Bean.SignBean;
import cn.bocweb.spinning.model.Bean.SignStatusBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.model.Bean.VersionBean;
import cn.bocweb.spinning.model.Imp.BaseModelImp;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.view.common.BaseActivity;
import cn.bocweb.spinning.view.common.GlideCircle;
import cn.bocweb.spinning.view.common.SecondTestService;
import cn.bocweb.spinning.view.common.UpdataService;
import cn.bocweb.spinning.view.dialog.CleanDialog;
import cn.bocweb.spinning.view.dialog.ConnectServiceDialog;
import cn.bocweb.spinning.view.dialog.SignDialog;
import cn.bocweb.spinning.view.forun.BBSActivity;
import cn.bocweb.spinning.view.forun.ForunMainFragment;
import cn.bocweb.spinning.view.fragment.InfoFragment;
import cn.bocweb.spinning.view.fragment.MainFragment;
import cn.bocweb.spinning.view.fragment.ProductCompanyFragment;
import cn.bocweb.spinning.view.fragment.QuestionListFragment;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends BaseActivity implements DrawerLayout.DrawerListener, View.OnClickListener {

    ProductCompanyFragment productCompanyFragment;
    ConnectServiceDialog connectServiceDialog;
    CleanDialog cleanDialog;
    SignDialog signDialog;
    long keyTime;
    public boolean isLogin;
    MainFragment mainFragment;
    InfoFragment infoFragment;
    ForunMainFragment forunMainFragment;
    QuestionListFragment questionListFragment;
    UserPresenter presenter;
    UserBean.DataEntity dataEntity;
    String downloadUrl = "";

    @Bind(R.id.fragment_main)
    FrameLayout fragmentMain;
    @Bind(R.id.btn_info)
    LinearLayout btnInfo;
    @Bind(R.id.btn_main)
    LinearLayout btnMain;
    @Bind(R.id.btn_my_info)
    LinearLayout btnMyInfo;
    @Bind(R.id.btn_msg)
    LinearLayout btnMsg;
    @Bind(R.id.btn_collect)
    LinearLayout btnCollect;
    @Bind(R.id.tv_sign)
    TextView tvSign;
    @Bind(R.id.btn_sign)
    LinearLayout btnSign;
    @Bind(R.id.btn_set_ques)
    LinearLayout btnSetQues;
    @Bind(R.id.btn_edit_pwd)
    RelativeLayout btnEditPwd;
    @Bind(R.id.btn_my_school)
    RelativeLayout btnMySchool;
    @Bind(R.id.btn_my_integral)
    RelativeLayout btnMyIntegral;
    @Bind(R.id.btn_my_file)
    RelativeLayout btnMyFile;
    @Bind(R.id.btn_clean)
    RelativeLayout btnClean;
    @Bind(R.id.btn_help)
    RelativeLayout btnHelp;
    @Bind(R.id.btn_connect)
    RelativeLayout btnConnect;
    @Bind(R.id.btn_exit)
    Button btnExit;
    @Bind(R.id.left_drawer)
    LinearLayout leftDrawer;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.main_icon)
    ImageView mainIcon;
    @Bind(R.id.main_unlogin)
    LinearLayout mainUnlogin;
    @Bind(R.id.main_realname)
    TextView mainRealname;
    @Bind(R.id.main_gender)
    ImageView mainGender;
    @Bind(R.id.main_level)
    TextView mainLevel;
    @Bind(R.id.main_phone)
    TextView mainPhone;
    @Bind(R.id.main_login)
    LinearLayout mainLogin;
    @Bind(R.id.main_warehouse)
    TextView mainWarehouse;
    @Bind(R.id.main_msg_icon)
    View mainMsgIcon;
    @Bind(R.id.btn_product_company)
    LinearLayout btnProductCompany;
    @Bind(R.id.btn_forun)
    LinearLayout btnForun;
    @Bind(R.id.btn_user)
    LinearLayout mBtnUser;
    @Bind(R.id.btn_register)
    Button btnRegister;
    @Bind(R.id.textview_version)
    TextView textviewVersion;
    @Bind(R.id.vier)
    View vier;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.TRANSPARENT);
            getWindow()
                    .getDecorView()
                    .setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);


        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            ViewGroup mContentView = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);

            //首先使 ChildView 不预留空间
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows(mChildView, false);
            }

            int statusBarHeight = DeviceUtil.getStatusBarHeight(this);
            //需要设置这个 flag 才能设置状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //避免多次调用该方法时,多次移除了 View
            if (mChildView != null && mChildView.getLayoutParams() != null && mChildView.getLayoutParams().height == statusBarHeight) {
                //移除假的 View.
                mContentView.removeView(mChildView);
                mChildView = mContentView.getChildAt(0);
            }
            if (mChildView != null) {
                FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mChildView.getLayoutParams();
                //清除 ChildView 的 marginTop 属性
                if (lp != null && lp.topMargin >= statusBarHeight) {
                    lp.topMargin -= statusBarHeight;
                    mChildView.setLayoutParams(lp);
                }
            }
        }

        setContentView(R.layout.activity_main);

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
//            vier.setVisibility(View.GONE);
//        } else {
        vier.setVisibility(View.VISIBLE);
//        }

        dataEntity = new UserBean.DataEntity();
        presenter = new UserPresenterImp();
        connectServiceDialog = new ConnectServiceDialog(this, "0571-57579788");
        connectServiceDialog.setOnMakePhoneListener(new ConnectServiceDialog.OnMakePhoneListener() {
            @Override
            public void makePhone() {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:0571-57579788"));
                if (Build.VERSION.SDK_INT >= 23) {
                    int callPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE);
                    if (callPermission != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(
                                MainActivity.this,
                                new String[]{Manifest.permission.CALL_PHONE},
                                302);
                    } else {

                        startActivity(intent);
                        drawerLayout.closeDrawer(Gravity.LEFT);
                    }
                } else {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//                    // TODO: Consider calling
//                    //    ActivityCompat#requestPermissions
//                    // here to request the missing permissions, and then overriding
//                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//                    //                                          int[] grantResults)
//                    // to handle the case where the user grants the permission. See the documentation
//                    // for ActivityCompat#requestPermissions for more details.
//                    return;
                        DeviceUtil.MyToast(MainActivity.this, "未获得拨打电话权限");
                        drawerLayout.closeDrawer(Gravity.LEFT);
                        return;
                    } else {
                        startActivity(intent);
                        drawerLayout.closeDrawer(Gravity.LEFT);
                    }
                }
                connectServiceDialog.dismiss();
            }
        });
        cleanDialog = new CleanDialog(this);
        signDialog = new SignDialog(this);
        mainFragment = new MainFragment();
        questionListFragment = new QuestionListFragment();
        drawerLayout.setScrimColor(Color.parseColor("#00000000"));
        infoFragment = new InfoFragment();
        forunMainFragment = new ForunMainFragment();
        productCompanyFragment = new ProductCompanyFragment();

        presenter.getVersion();


        if (mainFragment.isAdded()) {
            hideAllFragment()
                    .show(mainFragment)
                    .commitAllowingStateLoss();
        } else {
            hideAllFragment()
                    .add(R.id.fragment_main, mainFragment)
                    .show(mainFragment)
                    .commitAllowingStateLoss();
        }
        initState();

        try {
            textviewVersion.setText(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
//        ((ImageView) btnMain.getChildAt(0)).setImageResource(R.mipmap.main_library_on);
//        ((TextView) btnMain.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));


    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initState();
        initClickBtn();
        checkSecondUpdate();
        presenter.secondTime();
    }

    private void checkSecondUpdate() {
        SharedPreferences sp = getSharedPreferences(Constant.SECOND_UPDATE, Context.MODE_PRIVATE);
        boolean isSuccess = sp.getBoolean(Constant.SECOND_UPDATE_SUCCESS, false);
        String userid = sp.getString(Constant.SECOND_UPDATE_USER_ID, "");
        String testid = sp.getString(Constant.SECOND_UPDATE_TEST_ID, "");
        String detail = sp.getString(Constant.SECOND_UPDATE_DATA, "");
        if (!isSuccess && !TextUtils.isEmpty(userid)) {
            long timeline = System.currentTimeMillis();
            new BaseModelImp()
                    .mServer
                    .secondHandle2(String.valueOf(timeline),
                            DeviceUtil.getSign(String.valueOf(timeline)),
                            userid,
                            testid,
                            detail)
                    .enqueue(new Callback<SecondHandle2Bean>() {
                        @Override
                        public void onResponse(Response<SecondHandle2Bean> response, Retrofit retrofit) {
                            SharedPreferences sp = getSharedPreferences(Constant.SECOND_UPDATE, Context.MODE_PRIVATE);
                            sp.edit().putBoolean(Constant.SECOND_UPDATE_SUCCESS, true).apply();
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            SharedPreferences sp = getSharedPreferences(Constant.SECOND_UPDATE, Context.MODE_PRIVATE);
                            sp.edit().putBoolean(Constant.SECOND_UPDATE_SUCCESS, false).apply();
                        }
                    });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initState();
        drawerLayout.closeDrawer(Gravity.LEFT);
    }

    private boolean checkVersion(String versionServer, String versionLocal, int n) {
        int versionServerNum = Integer.parseInt(versionServer.split("\\.")[n]);
        int versionLoacaNum = Integer.parseInt(versionLocal.split("\\.")[n]);
        if (versionServerNum <= versionLoacaNum) {
            if (n < 2) {
                n++;
                return checkVersion(versionServer, versionLocal, n);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public void onEventMainThread(final VersionBean bean) {
        if (bean.getReturn_code() == 0) {
            downloadUrl = bean.getData().getAzurl();
            DeviceUtil.Log("download = " + downloadUrl);
            try {
                if (checkVersion(bean.getData().getAzversion(), getPackageManager().getPackageInfo(getPackageName(), 0).versionName, 0)) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                    dialog.setTitle("提示");
                    dialog.setMessage("有新版本,确定下载吗");
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (Build.VERSION.SDK_INT >= 23) {
                                int filePermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                                int readPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE);
                                if (filePermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED) {
                                    ActivityCompat.requestPermissions(
                                            MainActivity.this,
                                            new String[]{
                                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                                    Manifest.permission.READ_EXTERNAL_STORAGE},
                                            301);
                                    dialog.dismiss();
                                    return;
                                }
                            }
                            Intent intent = new Intent(MainActivity.this, UpdataService.class);
                            intent.putExtra("url", bean.getData().getAzurl());
                            startService(intent);
                            dialog.dismiss();
                        }
                    });
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    public void onEventMainThread(SecondTimeBean bean) {
        DeviceUtil.Log("bean = " + bean.getMsg());
        if (bean.getReturn_code() == 0) {
            SharedPreferences sp = getSharedPreferences(Constant.SECOND_TIME, Context.MODE_PRIVATE);
            String second_time_local = sp.getString(Constant.STRING_SECOND_TIME, "");
            DeviceUtil.Log("本地时间戳 = " + second_time_local);
            DeviceUtil.Log("后台时间戳 = " + bean.getData().getTimeline());
            DeviceUtil.Log("文件是否存在 = " + new File(getCacheDir().getAbsolutePath() + "/secondTest.txt").exists());
            if (!second_time_local.equals(bean.getData().getTimeline()) ||
                    !new File(getCacheDir().getAbsolutePath() + "/secondTest.txt").exists()) {
                sp.edit().putString(Constant.STRING_SECOND_TIME, bean.getData().getTimeline()).apply();
                Intent intent = new Intent(this, SecondTestService.class);
                startService(intent);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case Constant.LOGIN_TO_MAIN: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                if (!(dataEntity.getUserid() == null || dataEntity.getUserid().isEmpty())) {
                    Glide.with(this).load(dataEntity.getUthumb()).transform(new GlideCircle(this)).into(mainIcon);
                    mainUnlogin.setVisibility(View.GONE);
                    mainLogin.setVisibility(View.VISIBLE);
                    mainPhone.setText(dataEntity.getPhone());

                    int gender = 0;
                    if (Integer.parseInt(dataEntity.getGender()) == 1) {
                        gender = R.mipmap.rank_male;
                        mainGender.setVisibility(View.VISIBLE);
                    } else if (Integer.parseInt(dataEntity.getGender()) == 2) {
                        gender = R.mipmap.rank_female;
                        mainGender.setVisibility(View.VISIBLE);
                    } else {
                        mainGender.setVisibility(View.GONE);
                    }
                    mainGender.setImageResource(gender);
                    mainRealname.setText(dataEntity.getNickname());
                    btnExit.setVisibility(View.VISIBLE);
                }
                break;
            }
            case Constant.SET_WARE_TO_MAIN: {
                LibListBean.DataEntity dataEntity = new LibListBean.DataEntity();
                dataEntity.readLibListIntoLocal(this);
                if (!(dataEntity.getId() == null || dataEntity.getId().isEmpty())) {
                    mainWarehouse.setText(dataEntity.getTitle());
                    DeviceUtil.Log(dataEntity.getTitle());
                } else {
                    mainWarehouse.setText("未设置");
                }
                break;
            }
            case Constant.SEQUENCE_BACK_MAIN: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.readInfoFromLocal(this);
                if (!(dataEntity.getUserid() == null || dataEntity.getUserid().isEmpty())) {
                    Glide.with(this).load(dataEntity.getUthumb()).transform(new GlideCircle(this)).into(mainIcon);
                    mainUnlogin.setVisibility(View.GONE);
                    mainLogin.setVisibility(View.VISIBLE);
                    mainPhone.setText(dataEntity.getPhone());
                    int gender = (Integer.parseInt(dataEntity.getGender()) == 1) ? R.mipmap.rank_male : R.mipmap.rank_female;
                    mainGender.setImageResource(gender);
                    mainRealname.setText(dataEntity.getNickname());
                    btnExit.setVisibility(View.VISIBLE);
                }
                break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 301: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(MainActivity.this, UpdataService.class);
                    intent.putExtra("url", downloadUrl);
                    startService(intent);
                }
//                } else {
//                    ActivityCompat.requestPermissions(
//                            MainActivity.this,
//                            new String[]{
//                                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                                    Manifest.permission.READ_EXTERNAL_STORAGE},
//                            301);
//                }
                break;
            }
            case 302: {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:0571-57579788"));

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    DeviceUtil.MyToast(MainActivity.this, "未获得拨打电话权限");
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initState() {
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);
        initLoginState();
        isLogin = !(dataEntity.getUserid() == null || dataEntity.getUserid().isEmpty());
        if (isLogin) {
            initLoginView();
        } else {
            initUnloginView();
        }
    }

    private void initLoginState() {
        btnExit.setVisibility(View.GONE);
        mainUnlogin.setVisibility(View.GONE);
        mainLogin.setVisibility(View.GONE);
    }

    private void initLoginView() {
        btnRegister.setVisibility(View.GONE);
        btnExit.setVisibility(View.VISIBLE);
        mainUnlogin.setVisibility(View.GONE);
        mainLogin.setVisibility(View.VISIBLE);
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(this);

        if (!(dataEntity.getGender() == null || dataEntity.getGender().isEmpty())) {
            if (dataEntity.getGender().equals("1")) {
                mainGender.setVisibility(View.VISIBLE);
                mainGender.setImageResource(R.mipmap.rank_male);
            } else if (dataEntity.getGender().equals("2")) {
                mainGender.setVisibility(View.VISIBLE);
                mainGender.setImageResource(R.mipmap.rank_female);
            } else {
                mainGender.setVisibility(View.GONE);
            }
        } else {
            mainGender.setVisibility(View.GONE);
        }
        String phone = dataEntity.getPhone();
        if (phone == null || phone.isEmpty()) {
            mainPhone.setText("未登记手机");
        } else {
            mainPhone.setText(dataEntity.getPhone());
        }
        String nickname = dataEntity.getNickname();
        if (nickname == null || nickname.isEmpty()) {
            mainRealname.setText("未命名用户");
        } else {
            mainRealname.setText(dataEntity.getNickname());
        }
        if (!(dataEntity.getUthumb() == null || dataEntity.getUthumb().isEmpty())) {
            Glide.with(this).load(dataEntity.getUthumb()).transform(new GlideCircle(this)).into(mainIcon);
        } else {
            mainIcon.setImageResource(R.mipmap.drawer_icon_unlogin);
        }

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        String libTitle = lib.getTitle();
        if (libTitle == null || libTitle.isEmpty()) {
            mainWarehouse.setText("未设置");
        } else {
            mainWarehouse.setText(lib.getTitle());
        }
    }

    private void initUnloginView() {
        btnRegister.setVisibility(View.VISIBLE);
        btnExit.setVisibility(View.GONE);
        mainUnlogin.setVisibility(View.VISIBLE);
        mainLogin.setVerticalGravity(View.GONE);
        mainIcon.setImageResource(R.mipmap.drawer_icon_unlogin);

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);
        String libTitle = lib.getTitle();
        if (libTitle == null || libTitle.isEmpty()) {
            mainWarehouse.setText("未设置");
        } else {
            mainWarehouse.setText(lib.getTitle());
        }
    }

    private void initClickBtn() {
        btnMyInfo.setOnClickListener(this);
        btnEditPwd.setOnClickListener(this);
        btnMySchool.setOnClickListener(this);
        btnMyIntegral.setOnClickListener(this);
        btnMyFile.setOnClickListener(this);
        btnClean.setOnClickListener(this);
        btnHelp.setOnClickListener(this);
        btnConnect.setOnClickListener(this);
        btnExit.setOnClickListener(this);
        drawerLayout.setDrawerListener(this);
        btnMsg.setOnClickListener(this);
        btnConnect.setOnClickListener(this);
        btnSign.setOnClickListener(this);
        btnCollect.setOnClickListener(this);
        btnSetQues.setOnClickListener(this);
        btnInfo.setOnClickListener(this);
        btnMain.setOnClickListener(this);
        btnProductCompany.setOnClickListener(this);
        btnForun.setOnClickListener(this);
        mBtnUser.setOnClickListener(this);
        btnRegister.setOnClickListener(this);
    }

    public static MainActivity getInstance() {
        return new MainActivity();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.btn_main: {
                //跳转到考场
                initMain();

                break;
            }
            case R.id.btn_info: {
                //跳转到技术问答
                initInfo();

                break;
            }
            case R.id.btn_product_company: {
                initCompany();
                break;
            }
            case R.id.btn_forun: {
                initForun();
                break;
            }
            case R.id.btn_user: {
                initUser();
                break;
            }
            case R.id.btn_my_info: {
                if (isLogin) {
                    intent = new Intent(this, MyInfoActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_edit_pwd: {
                if (isLogin) {
                    intent = new Intent(this, ChangePwdActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_my_school: {
                if (isLogin) {
                    intent = new Intent(this, MySchoolListActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_my_integral: {
                if (isLogin) {
                    intent = new Intent(this, MyIntegralActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_my_file: {
                if (isLogin) {
                    intent = new Intent(this, MyFileActivity.class);
                    startActivity(intent);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_clean: {
                if (isLogin) {
                    cleanDialog.show();
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_help: {
                if (isLogin) {
                    intent = new Intent(this, HelpActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_connect: {
                connectServiceDialog.show();
                break;
            }
            case R.id.btn_exit: {
                UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                dataEntity.clearInfoFromLocal(this);
                intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.btn_msg: {
                if (isLogin) {
                    intent = new Intent(this, MyMsgActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_collect: {
                if (isLogin) {
                    intent = new Intent(this, MyCollectActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_sign: {
                if (isLogin) {
                    UserBean.DataEntity dataEntity = new UserBean.DataEntity();
                    dataEntity.readInfoFromLocal(this);
                    presenter.sign(dataEntity.getUserid());
                } else {
                    intent = new Intent(this, LoginAcivity.class);
                    intent.putExtra(Constant.IS_MAIN_TO_LOGIN, true);
                    startActivityForResult(intent, Constant.LOGIN_TO_MAIN);
                    drawerLayout.closeDrawer(Gravity.LEFT);
                }
                break;
            }
            case R.id.btn_set_ques: {
                intent = new Intent(this, SetQuesWarehouseActivity.class);
                startActivityForResult(intent, Constant.SET_WARE_TO_MAIN);
                drawerLayout.closeDrawer(Gravity.LEFT);
                break;
            }
            case R.id.btn_register: {
                intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                drawerLayout.closeDrawer(Gravity.LEFT);
                break;
            }
            default: {

            }
        }
    }


    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {
        View mContent = drawerLayout.getChildAt(0);
        View mMenu = drawerView;
        float scale = 1 - slideOffset;
        float rightScale = 0.8f + scale * 0.2f;
        float leftScale = 1 - 0.3f * scale;

        ViewHelper.setScaleX(mMenu, leftScale);
        ViewHelper.setScaleY(mMenu, leftScale);
        ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
        ViewHelper.setTranslationX(mContent,
                mMenu.getMeasuredWidth() * (1 - scale));
        ViewHelper.setPivotX(mContent, 0);
        ViewHelper.setPivotY(mContent,
                mContent.getMeasuredHeight() / 2);
        mContent.invalidate();
        ViewHelper.setScaleX(mContent, rightScale);
        ViewHelper.setScaleY(mContent, rightScale);
    }

    @Override
    public void onDrawerOpened(View drawerView) {
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//            vier.setVisibility(View.GONE);
//        }
        UserBean.DataEntity user = new UserBean.DataEntity();
        user.readInfoFromLocal(this);

        LibListBean.DataEntity lib = new LibListBean.DataEntity();
        lib.readLibListIntoLocal(this);

        presenter.getMsg(user.getUserid(), "1", "1", "1");

        initButton();
        ((ImageView) mBtnUser.getChildAt(0)).setImageResource(R.mipmap.user_select);
        ((TextView) mBtnUser.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));

        if (!TextUtils.isEmpty(user.getUserid())) {
            presenter.signStatus(user.getUserid());
        } else {
            tvSign.setText("签到");
        }
    }

    public void onEventMainThread(SignStatusBean bean) {
        if (bean.getReturn_code() == 0) {
            if (bean.getData().getSign().equals("1")) {
                tvSign.setText("已签到");
            } else {
                tvSign.setText("签到");
            }
        }
    }

    @Override
    public void onDrawerClosed(View drawerView) {
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            vier.setVisibility(View.VISIBLE);
//        }
        if (mainFragment.isVisible()) {
            initButton();
        } else if (infoFragment.isVisible()) {
            initButton();
        } else if (forunMainFragment.isVisible()) {
            initButton();
        }
    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (System.currentTimeMillis() - keyTime > 2000) {
                keyTime = System.currentTimeMillis();
                DeviceUtil.MyToast(this, "再按一次退出程序程序");
            } else {
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initButton() {
        //这个功能不要写死, 将来必改
        ((ImageView) btnMain.getChildAt(0)).setImageResource(R.mipmap.btn_company);
        ((TextView) btnMain.getChildAt(1)).setTextColor(getResources().getColor(R.color.content));
        // 欧了

        ((ImageView) btnInfo.getChildAt(0)).setImageResource(R.mipmap.btn_bbs);
        ((TextView) btnInfo.getChildAt(1)).setTextColor(getResources().getColor(R.color.content));

//        ((ImageView) btnProductCompany.getChildAt(0)).setImageResource(R.mipmap.btn_company);
//        ((TextView) btnProductCompany.getChildAt(1)).setTextColor(getResources().getColor(R.color.content));

        ((ImageView) btnForun.getChildAt(0)).setImageResource(R.mipmap.btn_info);
        ((TextView) btnForun.getChildAt(1)).setTextColor(getResources().getColor(R.color.content));

        ((ImageView) mBtnUser.getChildAt(0)).setImageResource(R.mipmap.user_unselect);
        ((TextView) mBtnUser.getChildAt(1)).setTextColor(getResources().getColor(R.color.content));
    }

    public void onEventMainThread(GetMsgBean bean) {
        if (bean.getReturn_code() == 0) {
            if (!bean.getUnread().equals("0")) {
                mainMsgIcon.setVisibility(View.VISIBLE);
            } else {
                mainMsgIcon.setVisibility(View.GONE);
            }
        }
    }

    public void onEventMainThread(SignBean bean) {
        if (bean.getReturn_code() == 0) {
            signDialog.setSignCount(bean.getData().getSign());
            signDialog.show();
            tvSign.setText("已签到");
        } else {
            DeviceUtil.MyToast(this, bean.getMsg());
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        hideLoading();
        DeviceUtil.MyToast(this, bean.getErrorMsg());
    }

    public void initMain() {
        initButton();
//        ((ImageView) btnMain.getChildAt(0)).setImageResource(R.mipmap.main_library_on);
//        ((TextView) btnMain.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));
        dataEntity.readInfoFromLocal(this);
        if (TextUtils.isEmpty(dataEntity.getUserid())) {
            Intent intent = new Intent(this, LoginAcivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, ReadyTestActivity.class);
            startActivity(intent);
        }
//        if (mainFragment.isAdded()) {
//            hideAllFragment().show(mainFragment).commit();
//        } else {
//            hideAllFragment().add(R.id.fragment_main, mainFragment).show(mainFragment).commit();
//        }
    }

    public void initInfo() {
        initButton();
        ((ImageView) btnInfo.getChildAt(0)).setImageResource(R.mipmap.main_bbs_on);
        ((TextView) btnInfo.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));
//        Intent intent = new Intent(this, QuestionListActivity.class);
//        startActivity(intent);
        if (questionListFragment.isAdded()) {
            hideAllFragment().show(questionListFragment).commit();
        } else {
            hideAllFragment().add(R.id.fragment_main, questionListFragment).show(questionListFragment).commit();
        }

    }

    public void initCompany() {
        initButton();
        if (mainFragment.isAdded()) {
            hideAllFragment().show(mainFragment).commitAllowingStateLoss();
        } else {
            hideAllFragment().add(R.id.fragment_main, mainFragment).show(mainFragment).commitAllowingStateLoss();
        }
    }

    public void initForun() {
        initButton();
        ((ImageView) btnForun.getChildAt(0)).setImageResource(R.mipmap.main_info_on);
        ((TextView) btnForun.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));
        if (infoFragment.isAdded()) {
            hideAllFragment().show(infoFragment).commitAllowingStateLoss();
        } else {
            hideAllFragment().add(R.id.fragment_main, infoFragment).show(infoFragment).commitAllowingStateLoss();
        }
    }

    public void initUser() {
        initButton();
        ((ImageView) mBtnUser.getChildAt(0)).setImageResource(R.mipmap.user_select);
        ((TextView) mBtnUser.getChildAt(1)).setTextColor(getResources().getColor(R.color.colorPrimary));
        drawerLayout.openDrawer(Gravity.LEFT);
    }

    private FragmentTransaction hideAllFragment() {
        return getSupportFragmentManager()
                .beginTransaction()
                .hide(mainFragment)
                .hide(infoFragment)
                .hide(questionListFragment)
                .hide(productCompanyFragment)
                .hide(forunMainFragment);
    }

    public void gotoFourm() {
//        if (forunMainFragment.isAdded()) {
//            hideAllFragment().show(forunMainFragment).commitAllowingStateLoss();
//        } else {
//            hideAllFragment().add(R.id.fragment_main, forunMainFragment).show(forunMainFragment).commitAllowingStateLoss();
//        }
        Intent intent = new Intent(this, BBSActivity.class);
        startActivity(intent);
    }
}
